/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.authorize.domain.repository;

import org.cshoo.tattoo.authorize.domain.po.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author 杨翼
 * @since 1.0
 */
public interface IUserRepository extends CrudRepository<User, Long> {

    /**
     * 分页查询角色数据
     *
     * @param pageable 分页信息
     * @return 用户
     */
    Page<User> findAll(Pageable pageable);

    User findUserByUsername(String username);

    /**
     * 修改用户信息
     *
     * @param user 用户
     */
    @Query("update User user set user.name = :#{#user.name}, user.lastModifiedBy = :#{#user.lastModifiedBy}, user.lastModifiedDate = :#{#user.lastModifiedDate} where user.id = :#{#user.id}")
    @Transactional
    @Modifying
    void updateUser(User user);

    /**
     * 根据群组id查询用户
     *
     * @param groupId 群组id
     * @return 用户
     */
    @Query(value = "select user from User user left join GroupUserRelation gur on user.id = gur.userId where gur.groupId = ?1")
    List<User> findUsersByGroupId(Long groupId);

    /**
     * 根据用户名称模糊查询用户
     *
     * @param name 名称，用户名或者用户姓名
     * @return 用户
     */
    @Query(value = "select user from User user where user.name like CONCAT('%',?1,'%') or user.username like CONCAT('%',?1,'%')")
    List<User> findUserByName(String name);

}
